package com.myapplication.zhou.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.myapplication.adapter.TopGridRecycleViewAdapter;
import com.myapplication.adapter.TopRecycleViewAdapter;
import com.myapplication.callback.TopPageCallback;
import com.myapplication.callback.TopScollViewCallback;
import com.myapplication.helper.PreferencesHelper1;
import com.myapplication.interfaces.TopPageConnect;
import com.myapplication.model.HeadImage;
import com.myapplication.model.Home1;
import com.myapplication.model.Home2;
import com.myapplication.model.Home4;
import com.myapplication.model.Home6;
import com.myapplication.model.Nav;
import com.myapplication.model.TopPageGoods;
import com.myapplication.viewpager.ChangableViewPager;
import com.myapplication.zhou.alldemo.R;
import com.myapplication.zhou.alldemo.SearchPageActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TopViewFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TopViewFragment extends Fragment implements TopPageCallback, TopScollViewCallback, SwipeRefreshLayout.OnRefreshListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER

    private TopPageConnect topPageConnect;
    @ViewInject(R.id.viewPager)
    private ViewPager viewPager;
    @ViewInject(R.id.layout_scan)
    private LinearLayout layout_scan;
    @ViewInject(R.id.viewGroup)
    private LinearLayout viewGroup;
    /*   @ViewInject(R.id.toolbar)
       private Toolbar toolbar;*/
    private List<HeadImage> listimages = new ArrayList<>();
    private List<View> listView = new ArrayList<>();
    private ArrayList<View> pageViews = new ArrayList<>();
    private ChangableViewPager viewPagerAdapter;
    private ImageView[] imageViews;
    @ViewInject(R.id.imageView1)
    private ImageView imageView1;
    @ViewInject(R.id.recycleView1)
    private RecyclerView recyclerView;
    @ViewInject(R.id.recycleView2)
    private RecyclerView recyclerView1;
    private TopRecycleViewAdapter topRecycleViewAdapter;
    private TopGridRecycleViewAdapter topGridRecycleViewAdapter;
    private List<Home1> home1List = new ArrayList<>();
    private List<Home2> home2List = new ArrayList<>();
    private List<Home6> home6List = new ArrayList<>();
    private List<Home4> home4List = new ArrayList<>();
    private List<Nav> navList = new ArrayList<>();
    private List<TopPageGoods> topPageGoodsList = new ArrayList<>();
    @ViewInject(R.id.swipeRefresh)
    private SwipeRefreshLayout swipeRefreshLayout;

    public TopViewFragment() {
        // Required empty public constructor
    }

    public static TopViewFragment newInstance() {
        TopViewFragment fragment = new TopViewFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_top_view, container, false);
        x.view().inject(this,view);
        /*swipeRefreshLayout.setColorSchemeColors(R.color.color_blue,R.color.colorPrimary,R.color.color_green_blue);*/
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_light, android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_red_light);
        // swipeRefreshLayout.setRefreshing(true);
        topPageConnect = new TopPageConnect();
       /* toolbar.setTitle("");
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);*/
        viewPager.addOnPageChangeListener(new ChangeViewPagerListener());
        topRecycleViewAdapter = new TopRecycleViewAdapter(getContext(), home4List, home1List);
        topGridRecycleViewAdapter = new TopGridRecycleViewAdapter(getContext(), topPageGoodsList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        GridLayoutManager layoutManager1 = new GridLayoutManager(getContext(), 2, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(topRecycleViewAdapter);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(true);
        recyclerView1.setLayoutManager(layoutManager1);
        recyclerView1.setAdapter(topGridRecycleViewAdapter);
        recyclerView1.setNestedScrollingEnabled(false);
        recyclerView1.setHasFixedSize(true);
        swipeRefreshLayout.setOnRefreshListener(this);
        //swipeRefreshLayout.setRefreshing(true);


        //    Glide.with(this).load("http://img1.imgtn.bdimg.com/it/u=1646998358,657385661&fm=21&gp=0.jpg").into(imageView1);
        return view;
    }

    /**
     * 首页全局
     */
    @Override
    public void onTopPageSuccessCallback(String onTopPageSuccess) {

        Log.i("jjjj", onTopPageSuccess);
        parseJsonString(onTopPageSuccess);
    }

    /**
     * 首页全局
     *
     * @param onTopPageFail {@link com.myapplication.interfaces.TopPageInter}
     */
    @Override
    public void onTopPageFailCallback(String onTopPageFail) {

    }

    /**
     * 首页滑动视图
     */
    @Override
    public void onScollViewCallbackSuccess(String onScollViewSuccess) {

        if (onScollViewSuccess.contains("data")) {

      //      listimages = getHeadImages(onScollViewSuccess);
            HeadImage headImage = new HeadImage();
            headImage.setUrl("http://h.hiphotos.baidu.com/zhidao/pic/item/d6ca7bcb0a46f21fc1fcaef4f6246b600d33ae49.jpg");
            HeadImage headImage1 = new HeadImage();
            headImage1.setUrl("http://h.hiphotos.baidu.com/zhidao/pic/item/d6ca7bcb0a46f21fc1fcaef4f6246b600d33ae49.jpg");
            HeadImage headImage2 = new HeadImage();
            headImage2.setUrl("http://h.hiphotos.baidu.com/zhidao/pic/item/d6ca7bcb0a46f21fc1fcaef4f6246b600d33ae49.jpg");
            listimages.add(headImage1);
            listimages.add(headImage2);
            listimages.add(headImage);
            if (listimages.size() == 0) {

            } else {
                for (int i = 0; i < listimages.size(); i++) {
                    LinearLayout layout = new LinearLayout(getActivity());
                    ViewGroup.LayoutParams ltp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
                    ImageView view = new ImageView(getContext());
                    Glide.with(getContext()).load(listimages.get(i).getUrl()).error(R.mipmap.wutu).into(view);
                    view.setTag(i + "");
                    layout.addView(view, ltp);
                    pageViews.add(layout);
                }
                imageViews = new ImageView[pageViews.size()];

                for (int i = 0; i < pageViews.size(); i++) {
                    /**设置imageview padding正确方法*/
                    ImageView imageView = new ImageView(getActivity());
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(12, 12);
                    params.setMargins(10, 0, 10, 0);
                    imageView.setLayoutParams(params);
                    imageView.setClickable(false);
                    imageViews[i] = imageView;
                    if (i == 0) {
                        imageViews[i]
                                .setBackgroundResource(R.mipmap.bar);
                    } else {
                        imageViews[i].setBackgroundResource(R.mipmap.bar02);
                    }
                    viewGroup.addView(imageViews[i]);
                }
                viewPagerAdapter = new ChangableViewPager(pageViews);
                viewPager.setAdapter(viewPagerAdapter);

            }

        }

    }

    /**
     * 首页滑动视图
     */
    @Override
    public void onScollViewCallbackFail(String onScollViewFail) {

    }

    @Override
    public void onRefresh() {
        listimages.clear();
        pageViews.clear();
        viewGroup.removeAllViews();
        home4List.clear();
        topPageGoodsList.clear();
        swipeRefreshLayout.setRefreshing(true);
        topPageConnect.getDataForTopPage(this);
        topPageConnect.getTopScoll("android", this);
    }


    public class ChangeViewPagerListener implements ViewPager.OnPageChangeListener {

        int a;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (position == 0 && a == 0) {

            }

            for (int i = 0; i < imageViews.length; i++) {
                imageViews[position]
                        .setBackgroundResource(R.mipmap.bar);

                if (position != i) {
                    imageViews[i]
                            .setBackgroundResource(R.mipmap.bar02);
                }
            }

        }

        @Override
        public void onPageScrollStateChanged(int state) {
            a = state;
        }
    }

    public void parseJsonString(String info) {
        try {
            JSONObject jsonObject = new JSONObject(info);
            JSONArray jsonArray = jsonObject.optJSONArray("datas");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                Iterator<String> keys = jsonObject1.keys();
                Object next = keys.next();
                String name = next.toString();
                if (name.equals("home1")) {
                    parseHome1(jsonObject1);
                    Log.i("jjjj1111", "jsjsjsjjs");
                } else if (name.equals("home2")) {
                    parseHome2(jsonObject1);
                    Log.i("jjj22222", "jsjsjsjjs");
                } else if (name.equals("home4")) {
                    parseHome4(jsonObject1);
                    Log.i("jjj33333", "jsjsjsjjs");
                } else if (name.equals("home6")) {
                    parseHome6(jsonObject1);
                    Log.i("jjj44444", "jsjsjsjjs");
                } else if (name.equals("goods")) {
                    parseGoods(jsonObject1);
                } else if (name.equals("nav")) {
                    parseNav(jsonObject1);
                    Log.i("jjj55555", "jsjsjsjjs");
                }
            }

            topRecycleViewAdapter.update(home4List);
            topGridRecycleViewAdapter.update(topPageGoodsList);

            swipeRefreshLayout.setRefreshing(false);


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void parseNav(JSONObject jsonObject1) {
        JSONArray jsonArray = jsonObject1.optJSONArray("nav");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.optJSONObject(i);
            String gc_id = jsonObject.optString("gc_id");
            String gc_thumb = jsonObject.optString("gc_thumb");
            String type = jsonObject.optString("type");
            String type_info = jsonObject.optString("typeinfo");
            String title = jsonObject.optString("title");
            Nav nav = new Nav();
            nav.setTitle(title);
            nav.setGc_id(gc_id);
            nav.setGc_thumb(gc_thumb);
            nav.setType(type);
            nav.setTypeinfo(type_info);
            navList.add(nav);
        }

    }

    private void parseGoods(JSONObject jsonObject1) {

        JSONObject jsonObject = jsonObject1.optJSONObject("goods");
        String title = jsonObject.optString("title");
        JSONArray jsonArray = jsonObject.optJSONArray("item");
        for (int i = 0; i < jsonArray.length(); i++) {
            TopPageGoods topPageGoods = new TopPageGoods();
            JSONObject jsonObject2 = jsonArray.optJSONObject(i);
            String goods_id = jsonObject2.optString("goods_id");
            String goods_name = jsonObject2.optString("goods_name");
            String goods_promotion_price = jsonObject2.optString("goods_promotion_price");
            String goods_image = jsonObject2.optString("goods_image");
            topPageGoods.setGoods_id(goods_id);
            topPageGoods.setGoods_image(goods_image);
            topPageGoods.setGoods_name(goods_name);
            topPageGoods.setGoods_promotion_price(goods_promotion_price);
            topPageGoodsList.add(topPageGoods);
        }
    }

    private void parseHome6(JSONObject jsonObject1) {
        JSONObject jsonObject = jsonObject1.optJSONObject("home6");
        String title = jsonObject.optString("title");
        String square_image = jsonObject.optString("square_image");
        String square_type = jsonObject.optString("square_type");
        String square_data = jsonObject.optString("square_data");
        String rectangle1_image = jsonObject.optString("rectangle1_image");
        String rectangle1_type = jsonObject.optString("rectangle1_type");
        String rectangle1_data = jsonObject.optString("rectangle1_data");
        String rectangle2_type = jsonObject.optString("rectangle2_type");
        String rectangle2_image = jsonObject.optString("rectangle2_image");
        String rectangle2_data = jsonObject.optString("rectangle2_data");

        Home6 home6 = new Home6();
        home6.setTitle(title);
        home6.setSquare_image(square_image);
        home6.setSquare_type(square_type);
        home6.setSquare_data(square_data);
        home6.setRectangle1_image(rectangle1_image);
        home6.setRectangle1_data(rectangle1_data);
        home6.setRectangle1_type(rectangle1_type);
        home6.setRectangle2_data(rectangle2_data);
        home6.setRectangle2_type(rectangle2_type);
        home6.setRectangle2_image(rectangle2_image);
        home6List.add(home6);
    }

    private void parseHome4(JSONObject jsonObject1) {
        JSONObject jsonObject = jsonObject1.optJSONObject("home4");
        String title = jsonObject.optString("title");
        String rectangle1_image = jsonObject.optString("rectangle1_image");
        String rectangle1_type = jsonObject.optString("rectangle1_type");
        String rectangle1_data = jsonObject.optString("rectangle1_data");
        String rectangle2_type = jsonObject.optString("rectangle2_type");
        String rectangle2_image = jsonObject.optString("rectangle2_image");
        String rectangle2_data = jsonObject.optString("rectangle2_data");
        String rectangle3_type = jsonObject.optString("rectangle3_type");
        String rectangle3_image = jsonObject.optString("rectangle3_image");
        String rectangle3_data = jsonObject.optString("rectangle3_data");
        String rectangle4_type = jsonObject.optString("rectangle4_type");
        String rectangle4_image = jsonObject.optString("rectangle4_image");
        String rectangle4_data = jsonObject.optString("rectangle4_data");
        String rectangle5_type = jsonObject.optString("rectangle5_type");
        String rectangle5_image = jsonObject.optString("rectangle5_image");
        String rectangle5_data = jsonObject.optString("rectangle5_data");
        String rectangle6_type = jsonObject.optString("rectangle6_type");
        String rectangle6_image = jsonObject.optString("rectangle6_image");
        String rectangle6_data = jsonObject.optString("rectangle6_data");
        String rectangle7_type = jsonObject.optString("rectangle7_type");
        String rectangle7_image = jsonObject.optString("rectangle7_image");
        String rectangle7_data = jsonObject.optString("rectangle7_data");
        String rectangle8_type = jsonObject.optString("rectangle8_type");
        String rectangle8_image = jsonObject.optString("rectangle8_image");
        String rectangle8_data = jsonObject.optString("rectangle8_data");
        String square_image = jsonObject.optString("square_image");
        Home4 home4 = new Home4();
        home4.setTitle(title);
        home4.setRectangle1_type(rectangle1_type);
        home4.setRectangle1_data(rectangle1_data);
        home4.setRectangle1_image(rectangle1_image);
        home4.setRectangle2_type(rectangle2_type);
        home4.setRectangle2_data(rectangle2_data);
        home4.setRectangle2_image(rectangle2_image);
        home4.setRectangle3_type(rectangle3_type);
        home4.setRectangle3_data(rectangle3_data);
        home4.setRectangle3_image(rectangle3_image);
        home4.setRectangle4_type(rectangle4_type);
        home4.setRectangle4_data(rectangle4_data);
        home4.setRectangle4_image(rectangle4_image);
        home4.setRectangle5_type(rectangle5_type);
        home4.setRectangle5_data(rectangle5_data);
        home4.setRectangle5_image(rectangle5_image);
        home4.setRectangle6_type(rectangle6_type);
        home4.setRectangle6_data(rectangle6_data);
        home4.setRectangle6_image(rectangle6_image);
        home4.setRectangle7_type(rectangle7_type);
        home4.setRectangle7_data(rectangle7_data);
        home4.setRectangle7_image(rectangle7_image);
        home4.setRectangle8_type(rectangle8_type);
        home4.setRectangle8_data(rectangle8_data);
        home4.setRectangle8_image(rectangle8_image);
        home4.setSquare_image(square_image);
        home4List.add(home4);
    }

    private void parseHome2(JSONObject jsonObject1) {
        JSONObject jsonObject = jsonObject1.optJSONObject("home2");
        String title = jsonObject.optString("title");
        String square_image = jsonObject.optString("square_image");
        String square_type = jsonObject.optString("square_type");
        String square_data = jsonObject.optString("square_data");
        String rectangle1_image = jsonObject.optString("rectangle1_image");
        String rectangle1_type = jsonObject.optString("rectangle1_type");
        String rectangle1_data = jsonObject.optString("rectangle1_data");
        String rectangle2_type = jsonObject.optString("rectangle2_type");
        String rectangle2_image = jsonObject.optString("rectangle2_image");
        String rectangle2_data = jsonObject.optString("rectangle2_data");
        String rectangle3_type = jsonObject.optString("rectangle3_type");
        String rectangle3_image = jsonObject.optString("rectangle3_image");
        String rectangle3_data = jsonObject.optString("rectangle3_data");
        Home2 home2 = new Home2();
        home2.setTitle(title);
        home2.setSquare_image(square_image);
        home2.setSquare_type(square_type);
        home2.setSquare_data(square_data);
        home2.setRectangle1_image(rectangle1_image);
        home2.setRectangle1_data(rectangle1_data);
        home2.setRectangle1_type(rectangle1_type);
        home2.setRectangle2_data(rectangle2_data);
        home2.setRectangle2_type(rectangle2_type);
        home2.setRectangle2_image(rectangle2_image);
        home2.setRectangle3_data(rectangle3_data);
        home2.setRectangle3_type(rectangle3_type);
        home2.setRectangle3_image(rectangle3_image);
        home2List.add(home2);

    }

    private void parseHome1(JSONObject jsonobject) {
        JSONObject jsonObject = jsonobject.optJSONObject("home1");
        String title = jsonObject.optString("title");
        String image = jsonObject.optString("image");
        String type = jsonObject.optString("type");
        String data = jsonObject.optString("data");
        Home1 home1 = new Home1();
        home1.setTitle(title);
        home1.setType(type);
        home1.setData(data);
        home1.setImage(image);
        home1List.add(home1);
    }

    public List<HeadImage> getHeadImages(String json) {
        List<HeadImage> list = new ArrayList<HeadImage>();
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONObject data = jsonObject.optJSONObject("datas");
            JSONObject adv_list = data.optJSONObject("adv_list");
            JSONArray jsonArray = adv_list.optJSONArray("item");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                HeadImage person = new HeadImage();
                person.setUrl(jsonObject1.getString("data"));
                person.setType(jsonObject1.getString("type"));
                person.setImage(jsonObject1.getString("image"));
                list.add(person);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private Handler handler = new Handler() {
        public void handlerMessage(Message message) {
            switch (message.what) {
                case 1:
                    int totalcount = viewPager.getChildCount();
                    int currentItem = viewPager.getCurrentItem();
                    int nextItem = currentItem + 1 == totalcount ? 0 : currentItem + 1;
                    viewPager.setCurrentItem(nextItem, true);
                    this.sendEmptyMessageDelayed(1, 3000);

            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        //activity启动两秒钟后，发送一个message，用来将viewPager中的图片切换到下一个
        //      handler.sendEmptyMessageDelayed(1, 2000);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                onRefresh();
            }
        });

    }

    @Override
    public void onStop() {
        super.onStop();
        //停止viewPager中图片的自动切换
        handler.removeMessages(1);
    }

    public void sentToOtherPage(Context context,String type, String data) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("keyword", data);

        intent.putExtras(bundle);
        if ("keyword".equals(type)) {
            bundle.putString("keyname",type);
            intent.setClass(context, SearchPageActivity.class);
            setSh1(context,"main","tag","topview");
            context.startActivity(intent);
        }else if("goods".equals(type)){

        }else if("url".equals(type)){

        }else if("special".equals(type)){

        }
    }

    public void setSh1(Context context, String name, String key, String value){
        PreferencesHelper1.setSharedValue(context,name,key,value);
    }

    public String getSh1(Context context,String name,String key){
        return PreferencesHelper1.getSharedValue(context,name,key);
    }
}
